<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>微信功能集成示例</title>
    <!-- 引入微信JS-SDK -->
    <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>
    <!-- 引入腾讯地图SDK -->
    <script charset="utf-8" src="https://map.qq.com/api/gljs?v=1.exp&key=N4DBZ-Q2W37-JNHXL-PI6NN-55FH5-2BF74"></script>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        #main-container {
            max-width: 600px;
            margin: 0 auto;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .map-section {
            padding: 20px;
            background-color: #fff;
        }
        #map-container {
            width: 100%;
            height: 300px;
            margin: 15px 0;
            border-radius: 4px;
            overflow: hidden;
        }
        .control-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            background-color: #f8f8f8;
        }
        .share-btn {
            padding: 12px 24px;
            margin: 10px;
            background: #1AAD19;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .share-btn:active {
            background-color: #179B16;
        }
        .location-info {
            padding: 15px;
            background-color: #fff;
            margin: 10px 0;
            border-radius: 4px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }
        .loading-spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #1AAD19;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        /* Toast 样式 */
        .toast-container {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 12px 20px;
            border-radius: 4px;
            font-size: 14px;
            z-index: 10000;
            max-width: 80%;
            text-align: center;
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        
        .toast-container.show {
            opacity: 1;
        }
        
        .toast-success {
            background: rgba(26, 173, 25, 0.9);
        }
        
        .toast-error {
            background: rgba(255, 0, 0, 0.8);
        }
    </style>
</head>
<body>
    <div id="main-container">
        <div class="map-section">
            <div id="map-container"></div>
            <div class="control-bar">
                <button class="share-btn" onclick="shareToTimeline()">分享到朋友圈</button>
                <button class="share-btn" onclick="shareToFriend()">分享给朋友</button>
            </div>
        </div>
        
        <div class="location-info" id="locationInfo" style="display: none;">
            <h3>当前位置详情</h3>
            <p><strong>经度：</strong><span id="lng"></span></p>
            <p><strong>纬度：</strong><span id="lat"></span></p>
            <p><strong>地址：</strong><span id="address"></span></p>
        </div>

        <div class="loading-overlay" id="loadingOverlay" style="display: none;">
            <div class="loading-spinner"></div>
        </div>
        
        <!-- Toast 容器 -->
        <div class="toast-container" id="toastContainer"></div>
    </div>

    <script>
        let wxConfig = null;
        let map = null;
        let markers = [];

        // 初始化微信配置
        async function initWxConfig() {
            try {
                const url = window.location.href.split('#')[0];
                const response = await fetch("https://www.api.nl9555.com/weChat/JSSDK", {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                        "token": JSON.parse(localStorage.getItem("token"))?.data || ""
                    },
                    body: JSON.stringify({ url })
                });

                if (!response.ok) throw new Error('网络响应失败');
                
                wxConfig = await response.json();
                wx.config({
                    debug: location.href.includes('debug') ? true : false,
                    appId: wxConfig.appId,
                    timestamp: wxConfig.timestamp,
                    nonceStr: wxConfig.nonceStr,
                    signature: wxConfig.signature,
                    jsApiList: ["chooseWXPay", "openLocation", "getLocation", "updateAppMessageShareData", "updateTimelineShareData"]
                });

                wx.ready(() => {
                    console.log("微信JS-SDK初始化成功");
                    initMap();
                    wx.hideOptionMenu();
                });

                wx.error((err) => {
                    console.error("微信初始化失败:", err);
                    showErrorToast('微信配置加载失败，请重试');
                    initMapWithH5Location();
                });
            } catch (error) {
                console.error("获取配置失败:", error);
                showErrorToast('网络连接异常');
                initMapWithH5Location();
            }
        }

        // 初始化地图
        function initMap() {
            map = new TMap.Map("map-container", {
                center: new TMap.LatLng(39.9088, 116.3975),
                zoom: 13,
                pitch: 50,
                styleId: "style1" // 可选样式
            });

            // 添加点击事件监听
            map.on("click", handleMapClick);
        }

        // 处理地图点击事件
        async function handleMapClick(e) {
            clearMarkers();
            const position = e.latLng;
            
            showLoading();
            try {
                const lat = position.getLat();
                const lng = position.getLng();
                
                // 显示标记
                const marker = new TMap.Marker({
                    position: new TMap.LatLng(lat, lng),
                    icon: "https://www.h5.nl9555.com/marker.png",
                    anchor: { x: 0.5, y: 1 }
                });
                markers.push(marker);
                map.addMarkers(markers);

                // 获取地址信息
                const addressInfo = await getAddressInfo(lat, lng);
                
                // 更新位置信息显示
                document.getElementById('lng').textContent = lng.toFixed(6);
                document.getElementById('lat').textContent = lat.toFixed(6);
                document.getElementById('address').textContent = addressInfo;
                document.getElementById('locationInfo').style.display = 'block';
                
                // 隐藏加载提示
                hideLoading();
            } catch (error) {
                console.error("地址解析失败:", error);
                hideLoading();
                showErrorToast('地址解析失败，请检查网络');
            }
        }

        // 获取地址信息（改为 fetch 请求）
        async function getAddressInfo(lat, lng) {
            const url = `https://apis.map.qq.com/ws/geocoder/v1/?location=${lat},${lng}&key=N4DBZ-Q2W37-JNHXL-PI6NN-55FH5-2BF74&get_poi=1`;
            const response = await fetch(url, { method: 'GET' });
            if (!response.ok) {
                throw new Error('网络响应失败');
            }
            const data = await response.json();
            if (data.status !== 0) {
                throw new Error(data.message || '解析失败');
            }
            const result = data.result;
            return `
                📍 精确地址：${result.address}<br>
                🗺️ 推荐地址：${result.formatted_addresses.recommend}<br>
                🏠 周边POI：<br>
                ${result.pois.map(poi => `• ${poi.title}`).join('\n')}
            `;
        }

        // H5定位回退方案
        function initMapWithH5Location() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    (position) => {
                        const { latitude, longitude } = position.coords;
                        map.setCenter(new TMap.LatLng(latitude, longitude));
                        showLoading();
                        getAddressInfo(latitude, longitude)
                            .then(info => {
                                document.getElementById('lng').textContent = longitude.toFixed(6);
                                document.getElementById('lat').textContent = latitude.toFixed(6);
                                document.getElementById('address').textContent = info;
                                document.getElementById('locationInfo').style.display = 'block';
                                hideLoading();
                            });
                    },
                    (error) => {
                        console.error("获取位置失败:", error);
                        showErrorToast('获取位置失败，请检查权限');
                    }
                );
            } else {
                showErrorToast('浏览器不支持地理定位');
            }
        }

        // 分享功能实现
        function shareToTimeline() {
            wx.updateTimelineShareData({
                title: "发现精彩位置",
                link: window.location.href,
                imgUrl: "https://www.h5.nl9555.com/share.png",
                success: () => showSuccessToast('朋友圈分享成功'),
                fail: () => showErrorToast('分享失败')
            });
        }

        function shareToFriend() {
            wx.updateAppMessageShareData({
                title: "我的位置分享",
                desc: "点击查看我的当前位置详情",
                link: window.location.href,
                imgUrl: "https://www.h5.nl9555.com/share.png",
                success: () => showSuccessToast('好友分享成功'),
                fail: () => showErrorToast('分享失败')
            });
        }

        // UI工具函数
        function showLoading() {
            document.getElementById('loadingOverlay').style.display = 'flex';
        }

        function hideLoading() {
            document.getElementById('loadingOverlay').style.display = 'none';
        }

        // 自定义 Toast 实现
        function showToast(options) {
            const toastContainer = document.getElementById('toastContainer');
            const { title, icon = 'success', duration = 1500 } = options;
            
            // 设置样式类
            toastContainer.className = 'toast-container';
            if (icon === 'success') {
                toastContainer.classList.add('toast-success');
            } else if (icon === 'none') {
                toastContainer.classList.add('toast-error');
            }
            
            // 设置内容
            toastContainer.textContent = title;
            
            // 显示 Toast
            toastContainer.classList.add('show');
            
            // 自动隐藏
            setTimeout(() => {
                toastContainer.classList.remove('show');
            }, duration);
        }

        function showErrorToast(message) {
            showToast({
                title: message,
                icon: 'none',
                duration: 2000
            });
        }

        function showSuccessToast(message) {
            showToast({
                title: message,
                icon: 'success',
                duration: 1500
            });
        }

        // 标记管理
        function clearMarkers() {
            markers.forEach(marker => map.removeMarkers(marker));
            markers = [];
        }

        // 页面加载初始化
        document.addEventListener("DOMContentLoaded", () => {
            initWxConfig();
        });
    </script>
</body>
</html>